package com.credit.web.basic;


import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.credit.context.CreditServletContext;
import com.credit.entity.CreditUserInfo;
import com.credit.exception.ErrorException;
import com.credit.service.RedisService;
import com.credit.service.UserService;
import com.credit.util.BeanToMapUtil;
import com.credit.util.CodeValueUtil;
import com.credit.util.Constants;
import com.credit.util.ImageUtil;
import com.credit.util.ParamsConstant;
import com.credit.util.PasswordUtil;
import com.credit.util.PhoneUtil;
import com.credit.util.SendVerifyCodeCase;
import com.credit.util.TokenUtil;
import com.credit.web.basic.bean.ResBean;
import com.credit.web.security.ImageCaptcha;

@Controller
@RequestMapping("/login")
public class LoginController {

	@Autowired
	private UserService userService;
	@Autowired
	private RedisService redisService;

	/**
	 * ֤登录方法
	 * 
	 * @param param
	 * @return
	 * @throws ErrorException
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public void login(HttpServletRequest request, HttpServletResponse response, @RequestParam("username") String username,
			@RequestParam("password") String password)
			throws ErrorException, IllegalArgumentException, IllegalAccessException {

		if (StringUtils.isEmpty(username)) {
			throw new ErrorException(Constants.MOBILE_NOTNULL_ERROR_CODE, Constants.MOBILE_NOTNULL_ERROR_DESC);
		}
		if (StringUtils.isEmpty(password)) {
			throw new ErrorException(Constants.MOBILE_NOTNULL_ERROR_CODE, Constants.MOBILE_NOTNULL_ERROR_DESC);
		}

		CreditUserInfo userInfo = userService.login(username, password);
		if (userInfo == null) {
			throw new ErrorException(Constants.USER_NOTEXISTS_ERROR_CODE, Constants.USER_NOTEXISTS_ERROR_DESC);
		}

		Map<String,Object> returnMap = BeanToMapUtil.getMap(userInfo);
		returnMap.remove("password");
		
		String token = TokenUtil.getToken(userInfo);
		
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("token",token );
		resBean.getData().put("userInfo", returnMap);
		CreditServletContext.setResBean(resBean);
		
	}
	

	
	@RequestMapping(value = "/captcha"/*, method = RequestMethod.GET*/)
	public void captcha( HttpServletRequest request,
			HttpServletResponse response) throws IOException {

			
			ImageCaptcha vCode = new ImageCaptcha(120, 50, 5, 10);

			// response.setHeader("Cache-Control", "no-store");
			// response.setHeader("Pragma", "no-cache");
			// response.setDateHeader("Expires", 0L);
			//response.setContentType("image/jpeg");
			//accountService.saveCaptchaCode(identityid, vCode.getCode());
			// request.getSession().setAttribute("randomcode", vCode.getCode());
			
	
			//vCode.write(response.getOutputStream());
			
			ResBean resBean = CreditServletContext.getResBean();
			resBean.getData().put("image", ImageUtil.imgToBase64String(vCode.getBuffImg(),"png"));
			CreditServletContext.setResBean(resBean);
			SendVerifyCodeCase.genRegisterVerifyCode(ParamsConstant.GRA_CODE_CACHE_PREFIX,resBean.getTimestamp()+"", vCode.getCode());
			
		
	}

	/**
	 * 注册方法
	 * @throws ErrorException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 * 
	 */
	@ResponseBody
	@RequestMapping(value="/register")
	public void register(String mobile,String smsCode,String password/*,String confirmPass*/) throws ErrorException, IllegalArgumentException, IllegalAccessException{
		
		if (StringUtils.isEmpty(mobile)) {
			throw new ErrorException(Constants.MOBILE_NOTNULL_ERROR_CODE, Constants.MOBILE_NOTNULL_ERROR_DESC);
		}
		
	/*	if (StringUtils.isEmpty(graCode)) {
			throw new ErrorException(Constants.GRACODE_NOTNULL_ERROR_CODE, Constants.GRACODE_NOTNULL_ERROR_DESC);
		}*/
		
		if (StringUtils.isEmpty(smsCode)) {
			throw new ErrorException(Constants.SMSCODE_NOTNULL_ERROR_CODE, Constants.SMSCODE_NOTNULL_ERROR_DESC);
		}
		
		if (StringUtils.isEmpty(password)) {
			throw new ErrorException(Constants.PASSWORD_NOTCORRECT_ERROR_CODE, Constants.PASSWORD_NOTCORRECT_ERROR_DESC);
		}
		
/*		if(StringUtils.isEmpty(timestamp)){
			throw new ErrorException(Constants.TIMESTAMP_NOTNULL_ERROR_CODE, Constants.TIMESTAMP_NOTNULL_ERROR_DESC);
		}
		*/
/*		if (StringUtils.isEmpty(confirmPass)) {
			throw new ErrorException(Constants.CONFIRMPASS_NOTNULL_ERROR_CODE, Constants.CONFIRMPASS_NOTNULL_ERROR_DESC);
		}*/
		
		if (!PhoneUtil.checkCellphone(mobile)) {
			throw new ErrorException(Constants.MOBILE_VERIFY_ERROR_CODE, Constants.MOBILE_VERIFY_ERROR_DESC);
		}
		
/*		if (!password.equals(confirmPass)) {
			throw new ErrorException(Constants.PASSWORD_NOTEQUAL_ERROR_CODE, Constants.PASSWORD_NOTEQUAL_ERROR_DESC);
		}*/
		
		if(!PasswordUtil.checkPassword(password)){
			throw new ErrorException(Constants.PASSWORD_VERIFY_ERROR_CODE, Constants.PASSWORD_VERIFY_ERROR_DESC);
		}
		
/*        if(!graCode.equalsIgnoreCase(SendVerifyCodeCase.getRegisterVerifyCode(ParamsConstant.GRA_CODE_CACHE_PREFIX, timestamp))){
        	throw new ErrorException(Constants.GRACODE_VERIFY_ERROR_CODE, Constants.GRACODE_VERIFY_ERROR_DESC);
        }*/
		
        if(!smsCode.equals(SendVerifyCodeCase.getRegisterVerifyCode(ParamsConstant.SMS_CODE_CACHE_PREFIX, mobile))){
        	throw new ErrorException(Constants.SMSCODE_VERIFY_ERROR_CODE, Constants.SMSCODE_VERIFY_ERROR_DESC);
        }
        
		CreditUserInfo userInfo = userService.findUserByMobile(mobile);
		
		if(userInfo!=null){
			throw new ErrorException(Constants.MOBILE_REGISTER_ERROR_CODE, Constants.MOBILE_REGISTER_ERROR_DESC);
		}
        
        userInfo = userService.register(mobile,password,CodeValueUtil.USERTYPE_MANAGER);
	
        Map<String,Object> returnMap = BeanToMapUtil.getMap(userInfo);
		returnMap.remove("password");
		
		String token = TokenUtil.getToken(userInfo);
		
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("token",token );
		resBean.getData().put("userInfo", returnMap);
		CreditServletContext.setResBean(resBean);
	}
	
	
	@ResponseBody
	@RequestMapping(value="/forgetPass")
	public void forgetPass(String mobile,String smsCode,String password/*,String confirmPass*/) throws ErrorException, IllegalArgumentException, IllegalAccessException{
		
		if (StringUtils.isEmpty(mobile)) {
			throw new ErrorException(Constants.MOBILE_NOTNULL_ERROR_CODE, Constants.MOBILE_NOTNULL_ERROR_DESC);
		}
		
/*		if (StringUtils.isEmpty(graCode)) {
			throw new ErrorException(Constants.GRACODE_NOTNULL_ERROR_CODE, Constants.GRACODE_NOTNULL_ERROR_DESC);
		}*/
		
		if (StringUtils.isEmpty(smsCode)) {
			throw new ErrorException(Constants.SMSCODE_NOTNULL_ERROR_CODE, Constants.SMSCODE_NOTNULL_ERROR_DESC);
		}
		
		if (StringUtils.isEmpty(password)) {
			throw new ErrorException(Constants.PASSWORD_NOTCORRECT_ERROR_CODE, Constants.PASSWORD_NOTCORRECT_ERROR_DESC);
		}
		
/*		if(StringUtils.isEmpty(timestamp)){
			throw new ErrorException(Constants.TIMESTAMP_NOTNULL_ERROR_CODE, Constants.TIMESTAMP_NOTNULL_ERROR_DESC);
		}*/
		
		
/*		if (StringUtils.isEmpty(confirmPass)) {
			throw new ErrorException(Constants.CONFIRMPASS_NOTNULL_ERROR_CODE, Constants.CONFIRMPASS_NOTNULL_ERROR_DESC);
		}*/
		
		if (!PhoneUtil.checkCellphone(mobile)) {
			throw new ErrorException(Constants.MOBILE_VERIFY_ERROR_CODE, Constants.MOBILE_VERIFY_ERROR_DESC);
		}
		
/*		if (!password.equals(confirmPass)) {
			throw new ErrorException(Constants.PASSWORD_NOTEQUAL_ERROR_CODE, Constants.PASSWORD_NOTEQUAL_ERROR_DESC);
		}
		*/
		if(!PasswordUtil.checkPassword(password)){
			throw new ErrorException(Constants.PASSWORD_VERIFY_ERROR_CODE, Constants.PASSWORD_VERIFY_ERROR_DESC);
		}
		
/*        if(!graCode.equalsIgnoreCase(SendVerifyCodeCase.getRegisterVerifyCode(ParamsConstant.GRA_CODE_CACHE_PREFIX, timestamp))){
        	throw new ErrorException(Constants.GRACODE_VERIFY_ERROR_CODE, Constants.GRACODE_VERIFY_ERROR_DESC);
        }*/
		
        if(!smsCode.equals(SendVerifyCodeCase.getRegisterVerifyCode(ParamsConstant.SMS_CODE_CACHE_PREFIX, mobile))){
        	throw new ErrorException(Constants.SMSCODE_VERIFY_ERROR_CODE, Constants.SMSCODE_VERIFY_ERROR_DESC);
        }
        
        CreditUserInfo userInfo = userService.forgetPass(mobile,password);
	
        Map<String,Object> returnMap = BeanToMapUtil.getMap(userInfo);
		returnMap.remove("password");
		
		String token = TokenUtil.getToken(userInfo);
		
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("token",token );
		resBean.getData().put("userInfo", returnMap);
		CreditServletContext.setResBean(resBean);
	}
	
	@ResponseBody
	@RequestMapping(value="/smsLogin")
	public void smsLogin(String mobile,String smsCode) throws ErrorException, IllegalArgumentException, IllegalAccessException{
		
		if (StringUtils.isEmpty(mobile)) {
			throw new ErrorException(Constants.MOBILE_NOTNULL_ERROR_CODE, Constants.MOBILE_NOTNULL_ERROR_DESC);
		}
		
/*		if (StringUtils.isEmpty(graCode)) {
			throw new ErrorException(Constants.GRACODE_NOTNULL_ERROR_CODE, Constants.GRACODE_NOTNULL_ERROR_DESC);
		}
		*/
		if (StringUtils.isEmpty(smsCode)) {
			throw new ErrorException(Constants.SMSCODE_NOTNULL_ERROR_CODE, Constants.SMSCODE_NOTNULL_ERROR_DESC);
		}
		
/*        if(!graCode.equalsIgnoreCase(SendVerifyCodeCase.getRegisterVerifyCode(ParamsConstant.GRA_CODE_CACHE_PREFIX, mobile))){
        	throw new ErrorException(Constants.GRACODE_VERIFY_ERROR_CODE, Constants.GRACODE_VERIFY_ERROR_DESC);
        }
		*/
        if(!smsCode.equals(SendVerifyCodeCase.getRegisterVerifyCode(ParamsConstant.SMS_CODE_CACHE_PREFIX, mobile))){
        	throw new ErrorException(Constants.SMSCODE_VERIFY_ERROR_CODE, Constants.SMSCODE_VERIFY_ERROR_DESC);
        }
        
        CreditUserInfo userInfo = userService.findUserByMobile(mobile);
        if(userInfo == null){
        	userInfo = userService.register(mobile,"123456",CodeValueUtil.USERTYPE_BORROWER);
        }
	
        Map<String,Object> returnMap = BeanToMapUtil.getMap(userInfo);
		returnMap.remove("password");
		
		String token = TokenUtil.getToken(userInfo);
		
		ResBean resBean = CreditServletContext.getResBean();
		resBean.getData().put("token",token );
		resBean.getData().put("userInfo", returnMap);
		CreditServletContext.setResBean(resBean);
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public void logout() throws IOException {
		String token = CreditServletContext.getRequest().getHeader("token");
		redisService.delete(token);
		
	}

}
